import 'package:flutter_app/bean/file_path_entity.dart';
import 'package:flutter_app/manager/UserInfoManager.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/ui/main/main_logic.dart';
import 'package:flutter_app/utils/queue_utils.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:flutter_app/utils/video_compress_utils.dart';
import 'package:flutter_app/widget/picker/camera_utils.dart';
import 'package:flutter_app/widget/watermark/watermark_utils.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_instance/src/extension_instance.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:video_compress/video_compress.dart';

import 'queue_state.dart';

class QueueLogic extends GetxController {
  final QueueState state = QueueState();
  final mainLogic = Get.find<MainLogic>();


  // 要上传的文件
  List<Media> imagesList = [];

  RxString uploadProgress = "".obs;

  @override
  void onInit() {
    super.onInit();
    state.taskList.value = QueueUtils.get("net")?.getTaskList() as List<TaskInfo>;
    update();
  }

  // 视频压缩
  Future<Media> videoCompress(Media medias) async {
    MediaInfo? mediaInfo = await VideoCompressUtils().compressVideo(
      medias.path ?? "",
    );
    final thumbnailFile = await VideoCompressUtils().getFileThumbnail(mediaInfo?.path ?? medias.path ?? "");
    Media media = new Media();
    media.path = mediaInfo?.path ?? medias.path;
    media.thumbPath = thumbnailFile.path;
    media.galleryMode = GalleryMode.video;
    return media;
  }

  List<FilePathEntity>? filePathEntity;

  /// 保存问题填报信息
  Future<bool> postSaveProblemSubmit(
      String groupId,
      String orgName,
      String orgId,
      String content,
      List<FilePathEntity> fileList,
      String problemCode,
      {String? id}) async {

    Map<String, dynamic> param = {
      "groupId": groupId,
      'orgName': orgName,
      'orgId': orgId,
      'content': content,
      'fileList': fileList,
      // 问题id
      'id': id,
      'problemCode': problemCode,
    };
    ResultData resultData = await Api.postSaveProblemSubmit(param);
    if (resultData.isSuccess) {
      return true;
    } else {
      toast.show(resultData.data["message"]);
      return false;
    }
  }



  void add(List<Media> imagesList) {
    /// 将任务添加到队列
    if (imagesList.length <= 0) {
      return toast.show("没值");
    }
    // List<Media> tasks = [];
    // imagesList.forEach((element) {
    //   QueueUtils.get("video")?.addTask("${element.path}视频压缩中", () {
    //     var task =  videoCompress(element).then((Media media){
    //       tasks.add(media);
    //       update();
    //
    //       if (tasks.length == imagesList.length) {
    //         QueueUtils.get("uploadFiles")?.addTask("文件上传", () {
    //           return uploadFiles(tasks).then((_) {
    //             update();
    //           });
    //         });
    //         state.taskList.value = QueueUtils.get("uploadFiles")?.getTaskList() as List<TaskInfo>;
    //         update();
    //       }
    //     });
    //     return task;
    //   });
    // });
    // state.taskList.value = QueueUtils.get("video")?.getTaskList() as List<TaskInfo>;
    //
    // update();

    QueueUtils.get("uploadFiles")?.addTask(
      "文件上传", doSomething: () {
      return mainLogic.uploadFiles(
        imagesList,
        uploadProgress: (sent, total) {
          this.uploadProgress.value = sent / total;
        },
      ).then((_) {
        state.taskList.value = QueueUtils.get("uploadFiles")?.getTaskList() as List<TaskInfo>;
        update();
      });
    }, onError: () {
        update();
      }
    );
  }

  Future _doFuture(String queueName, int taskNo) {
    return Future.delayed(Duration(seconds: 5), () {
      print("任务完成  queueName: $queueName, taskNo: $taskNo");
      update();
    });
  }

  Future<void> start() async {
    Media? media = await CameraUtils().openCameraAddWatermark();
    await uploadFilesInfo(media);
  }

  Future<void> uploadFilesInfo(Media? media) async {
    if (media?.path == null) {
      return;
    }
    List<Media> list = [media!];
    List<FilePathEntity>? entiy = await mainLogic.uploadFiles(list);
  }

  @override
  void onReady() {
    super.onReady();
    mainLogic.state.isShowFloatObs.value = false;

    WatermarkUtils().addWatermark(Get.context!, UserInfoManager().getUserName(), columnCount: 8, rowCount: 4);

  }

  @override
  void onClose() {
    super.onClose();
    Future.delayed(Duration(milliseconds: 500)).then((e) {
      mainLogic.state.isShowFloatObs.value = true;
    });
    WatermarkUtils().removeWatermark();
  }
}
